package com.quanyan.ic.protocol.codec;

import com.quanyan.ic.protocol.codec.protobuf.ICMessageProto;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by zhuo.shi on 2017/6/7.
 * +--------+---------------+                  +---------- ------+
 * | Length  | Protobuf Data |  --------------> | Protobuf Data  |
 * | 4 bytes |  (x bytes)    |                  | (x bytes)      |
 * +--------+---------------+                   +----------------+
 */
public class ICMessageDecoder extends LengthFieldBasedFrameDecoder {

    private static Logger logger = LoggerFactory.getLogger(ICMessageDecoder.class);

    public ICMessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {

        ByteBuf frame = (ByteBuf) super.decode(ctx, in);
        if (frame == null) return null;         //连接异常，消息无字节

        int length = frame.readInt();           //头，protobuf data长度
        logger.debug("protobuf data message length：" + length);

        int readLength = frame.readableBytes(); //剩余的protobuf段可读字节
        logger.debug("after length, readable bytes={}", readLength);
        ICMessageProto.ICMessage icMessage = ICMessageProto.ICMessage.parseFrom(frame.readBytes(length).array());
        frame.release();
        return icMessage;
    }
}
